package com.application.model;

import com.application.module.usermoney.UserMoneyFactory;
import com.jfinal.log.Log;
import com.platform.annotation.Table;
import com.platform.mvc.base.BaseModel;
import com.platform.mvc.user.User;

import java.math.BigDecimal;
import java.sql.Timestamp;

@SuppressWarnings("unused")
@Table(tableName = Rebate.table_name, pkName = "id")
public class Rebate extends BaseModel<Rebate> {

    private static final long serialVersionUID = 6761767368352810428L;

    private static final Log log = Log.getLog(Rebate.class);

    public static final Rebate dao = new Rebate().dao();

    /**
     * 表名称
     */
    public static final String table_name = "t_rebate";

    /**
     * sqlId : app.rebate.splitPageFrom
     * 描述：分页from
     */
    public static final String sqlId_splitPageFrom = "app.rebate.splitPageFrom";

    private Integer id;
    private String name;
    private BigDecimal vip_rate1;
    private BigDecimal vip_rate2;
    private BigDecimal normal_rate1;
    private BigDecimal normal_rate2;
    private Timestamp create_time;
    private Timestamp delete_time;

    public void setId(Integer id) {
        set("id", id);
    }

    public Integer getId() {
        return get("id");
    }

    public void setName(String name) {
        set("name", name);
    }

    public String getName() {
        return get("name");
    }

    public void setVip_rate1(BigDecimal vip_rate1) {
        set("vip_rate1", vip_rate1);
    }

    public BigDecimal getVip_rate1() {
        return get("vip_rate1");
    }

    public void setVip_rate2(BigDecimal vip_rate2) {
        set("vip_rate2", vip_rate2);
    }

    public BigDecimal getVip_rate2() {
        return get("vip_rate2");
    }

    public void setNormal_rate1(BigDecimal normal_rate1) {
        set("normal_rate1", normal_rate1);
    }

    public BigDecimal getNormal_rate1() {
        return get("normal_rate1");
    }

    public void setNormal_rate2(BigDecimal normal_rate2) {
        set("normal_rate2", normal_rate2);
    }

    public BigDecimal getNormal_rate2() {
        return get("normal_rate2");
    }

    public void setCreate_time(Timestamp create_time) {
        set("create_time", create_time);
    }

    public Timestamp getCreate_time() {
        return get("create_time");
    }

    public void setDelete_time(Timestamp delete_time) {
        set("delete_time", delete_time);
    }

    public Timestamp getDelete_time() {
        return get("delete_time");
    }

    /**
     * -是-返利%a,终止；否-返利b%
     * 判断上上级是否高级会员：
     * -是-返利c%；否-返利d%
     */
    public void rebate(Integer orderId, Integer userid, String orderNo) {
        User user = User.dao.findById(userid);
        Integer pid = user.getRefereeUserid();
        //如果没有上线，终止返利
        if (pid == null) {
            return;
        }

        //如果上线为空，终止返利
        User pUser = User.dao.findById(pid);
        if (pUser == null) {
            return;
        }

        /*
        1.计算返利并保存返利记录
         */
        BigDecimal m1;
        BigDecimal m2 = new BigDecimal(0);

        Order order = Order.dao.findById(orderId);
        Rebate rebate = getRebatePlan(order);
        if(rebate == null) return;
        BigDecimal tmp = (new BigDecimal(Double.toString(0.01)))
                .multiply(order.getTotal_amount());
        boolean isVip1 = User.isVip(pUser);
        m1 = tmp.multiply(isVip1 ? rebate.getVip_rate1() : rebate.getNormal_rate1()).setScale(2, BigDecimal.ROUND_HALF_UP);
        //记录明细
        RebateHistory history = new RebateHistory();
        history.setCreate_time(new Timestamp(System.currentTimeMillis()));
        history.setRebate_id(rebate.getId());
        history.setMoney_1(m1.toString());
        history.setRoleid_1(isVip1 ? "vip" : "normal");
        history.setUserid_1(pUser.getId());
        history.setOrder_no(orderNo);

        //记录二级返利
        Integer p2id = pUser.getRefereeUserid();
        User pUser2 = p2id != null ? User.dao.findById(p2id) : null;
        if (pUser2 != null) {
            boolean isVip2 = User.isVip(pUser2);
            m2 = tmp.multiply(isVip2 ? rebate.getVip_rate2() : rebate.getNormal_rate2()).setScale(2, BigDecimal.ROUND_HALF_UP);
            history.setMoney_2(m2.toString());
            history.setRoleid_2(isVip2 ? "vip" : "normal");
            history.setUserid_2(pUser2.getId());
        }
        if(m1.floatValue() > 0 || m2.floatValue() > 0){
            history.save();
        }

        log.info("###########m1:" + m1);
        log.info("###########m2:" + m2);

        /**
         * 2.记录用户余额变动明细
         */
        if (m1.floatValue() > 0) {
            pUser.set("gift", pUser.getBigDecimal("gift").add(m1)).update();
            User.cacheRemove(pid);
            UserMoneyFactory.getObject(orderNo).create(pUser.getId(), m1.toString(), orderNo, userid);
//            new RebateUserMoney().create(pUser.getId(), m1.toString(), orderNo, userid);
        }
        //二级返利
        if (pUser2 != null && m2.floatValue() > 0) {
            pUser2.set("gift", pUser2.getBigDecimal("gift").add(m2)).update();
            User.cacheRemove(p2id);
            UserMoneyFactory.getObject(orderNo).create(pUser2.getId(), m2.toString(), orderNo, userid);
        }

    }

    /*
    获取订单对应的返利方案(现为最新的第一条返利方案)
     */
    private Rebate getRebatePlan(Order orderId) {
        Rebate rebate = findFirst("select * from "+ table_name + " where delete_time is null order by id desc");
        return rebate;
    }
}